# Copyright (C) 2006 Max Verzier <maxverzier@gmail.com>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

# TODO
def set_date_format(format):
	"""return the time according to the format given"""
	pass

# FIXME : 		- make shure checks are correct
#				- make shure message styles versions are correctly implemented
def load_templates(style_path):
    """pre-fetch templates files"""
    
    template['header_html'] = read_file \
    (style_path + "/Contents/Resources/Header.html")
    template['footer_html'] = read_file \
    (style_path + "/Contents/Resources/Footer.html")
    template['base_html'] = read_file \
    (style_path + "/Contents/Resources/Template.html")
              
    if (((template['base_html'] == None) or len(template['base_html']) == 0) \
        and template['style_version'] >= 1 ):
        template['base_html'] = template['bundled_template']
        template['using_custom_base_html'] = False
    else:
        template['using_custom_base_html'] = True
    
    #Content Templates
    template['content_in_html'] = read_file \
    (style_path + "/Contents/Resources/Incoming/Content.html")
    template['next_content_in_html'] = read_file \
    (style_path + "/Contents/Resources/Incoming/NextContent.html")
    template['content_out_html'] = read_file \
    (style_path + "/Contents/Resources/Outgoing/Content.html")
    template['next_content_out_html'] = read_file \
    (style_path + "/Contents/Resources/Outgoing/NextContent.html")
      
    #Context Templates (fallback on content if not present
    template['context_in_html'] = read_file \
    (style_path + "/Contents/Resources/Incoming/Context.html")
    template['next_context_in_html'] = read_file \
    (style_path + "/Contents/Resources/Incoming/Context.html")
    if template['context_in_html'] == None:
        template['context_in_html'] = template['content_in_html']
    if template['next_context_in_html'] == None:
        template['next_context_in_html'] = template['next_content_in_html']        
      
    template['context_out_html'] = read_file \
    (style_path + "/Contents/Resources/Outgoing/Context.html")
    template['next_context_out_html'] = read_file \
    (style_path + "/Contents/Resources/Outgoing/Context.html")
    if template['context_out_html'] == None:
        template['context_out_html'] = template['content_out_html']
    if template['next_context_out_html'] == None:
        template['next_context_in_html'] = template['next_content_in_html']
        template['status_html'] = read_file \
    (style_path + "/Contents/Resources/Status.html")
       
    print "(load_template)TODO: Load filetransfert or input default style"
    print "(load_template)TODO: Valide Send Colors"



# FIXME :		- full debug
def base_template_with_variant(style_path):
    """set base template (= begening of conversation)"""
    print "base_template_with_variant: enlever @import"
    # old styles may be using an old custom 4 parameter baseHTML.
    # styles version 3 and higher should be using the bundled (or a custom)
    # 5 parameter baseHTML.
    if template['style_version'] < 3 and template['using_custom_base_html']:
        
        template_html = template['base_html']
        template_html = template_html.replace \
        ("%@", template['style_path'] + "Contents/Resources/", 1)
        #("%@", "./", 1)
        
        if template.has_key('DefaultVariant'):
            template_html = template_html.replace("%@", read_file( template['style_path'] + "/Contents/Resources/Variants/" + template['DefaultVariant'] + ".css" ) , 1)
        else:
            template_html = template_html.replace("%@", "", 1)

        if template['show_header'] and not template['header_html'] == None:
            template_html = template_html.replace('%@', template['header_html'], 1)
        if not template['footer_html'] == None:
            template_html = template_html.replace('%@', template['footer_html'], 1)
    
    else:
    
        template_html = template['base_html']
        template_html = template_html.replace \
        ("%@", template['style_path'] + "Contents/Resources/", 1)
        
        if template['style_version'] < 3:
            template_html = template_html.replace("%@", \
#                                                  "", 1)
            read_file( template['style_path'] + "/Contents/Resources/main.css" ) , 1)  
        else:
            #print template_html
            template_html = template_html.replace('%@', \
            #('%@import url( "%@" );', read_file( template['style_path'] + "/Contents/Resources/main.css" ) , 1)
            read_file( template['style_path'] + "/Contents/Resources/main.css" ) , 1)  

        if template.has_key('default_variant'):
            pos = template_html.index('</script>')
            right = template_html[pos:]
            left = template_html[:pos] 
            right = right.replace('@import url( "%@" );', \
            read_file( template['style_path'] + "/Contents/Resources/Variants/" \
                       + template['default_variant'] + ".css" ), 1)
            template_html = left + right      
            #print template_html        
             #( '%@import url( "%@" );' , \
#                          'foo' , 1) 
                        #read_file( template['style_path'] + \
                            #"/Contents/Resources/Variants/" + \
                           # template['DefaultVariant'] + ".css" )
        else:
            template_html = template_html.replace("%@", "", 1)
        
        
        if template['show_header'] == True or not template['header_html'] == None:
            template_html = template_html.replace('%@', template['header_html'], 1)
        else:
            template_html = template_html.replace('%@', "", 1)
            
        if not template['footer_html'] == None:
            template_html = template_html.replace('%@', template['footer_html'], 1)
        else:
            template_html = template_html.replace('%@', "", 1)
    
    return template_html



# TODO
def escape_string_for_passing_to_script(string):
	"""clean the html content before appending it to the javascript"""
	pass


# FIXME :		- add all mandatory informations + style correct name & credits
def read_style_infos(style_path):
	"""read the message style plist configuration file"""
    info_plist = plist.parsePlistFile(style_path)
    if info_plist.has_key('MessageViewVersion'):
        template['style_version'] = info_plist['MessageViewVersion']
    else:
        template['style_version'] = 1
    
    if info_plist.has_key('DefaultVariant'):
        template['default_variant'] = info_plist['DefaultVariant']




# FIXME :		- add all possible keyords
#				- handle time format (shared function with fill_keywords_for_base_template)
def fill_keywords(string, show_chat):
    """fill message style keywords before appending message"""
    simple_pattern = ['%time%', '%userIconPath%', '%senderScreenName%', \
                        '%sender%', '%service%', '%incomingIconPath%']
    simple_value = [time.strftime('%H:%M'), '%userIconPath%', \
                    '%senderScreenName%', show_chat.last_speaker, "MSN", \
                    '%incomingIconPath%']
    
    for i in range(len(simple_pattern)):
        string = string.replace(simple_pattern[i], simple_value[i])

    if string.count('@import') > 0:
        string = string.replace('@import url( ', '<link rel="stylesheet" type="text/css" href= ')
        string = string.replace(' );', ' />')
    
    # we always fill the message keyword at the end
    string = string.replace('%message%', show_chat.last_message)
    return string



# FIXME:		- add all possible keyords
#				- handle time format (shared function with fill_keywords)
#				- "@import url" treatment seems too gross
def fill_keywords_for_base_template(string, show_cat):
    """fill message style keywords before appending base template"""
    simple_pattern = ['%chatName%', '%sourceName%', '%destinationName%', \
                       '%destinationDisplayName%', '%incomingIconPath%']
    simple_value = ['%chatName%', '%sourceName%', '%destinationName%', \
                       '%destinationDisplayName%', '%incomingIconPath%']
    

    for i in range(len(simple_pattern)):
        string = string.replace(simple_pattern[i], simple_value[i])
       

    print "trouver une solution fill_key_base"
    for y in range(string.count('@import url(', string.index('</script>'))):
        pos1 = string.index('@import url(', string.index('</script>')) + 14
        pos2 = string.index(');', pos1)
        
        css_file = string[pos1:pos2]
        left = string[:pos2-14]
        right = string[pos1+4:]
        
        css_file = '<link rel="stylesheet" type="text/css" href= "' + css_file + '" />'
        string = left + css_file + right

        return string
        

def get_correct_template (content_type, direction, repeating):
    """return the correct template depending of the kind of message"""
    if content_type == "CONTENT_MESSAGE_TYPE":
        if direction == "isOutGoing":
            if repeating:
                template_type = template['next_content_out_html']
            else:
                template_type = template['content_out_html']
        else:
            if repeating:
                template_type = template['content_in_html']
            else:
                 template_type = template['next_content_in_html']      
                          
    elif content_type == "CONTEXT_MESSAGE_TYPE":
        if direction == "isOutGoing":
             if repeating:
                 template_type = template['next_context_out_html']           
             else:    
                 template_type = template['context_out_html']
        else:
            if repeating:
                template_type = template['next_context_out_html']            
            else:
                template_type = template['context_out_html']
                
    elif content_type == "CONTENT_FILE_TRANSFER_TYPE":
        print "sendMessage : Template, CONTENT_FILE_TRANSFER_TYPE"
        template_type = None
    else:
        template_type = template['status_html']
    return template_type    




def get_correct_script (repeating, scroll = 0):
    """return the correct JS script to use in order to append message"""
    if template['style_version'] >= 3:
        if scroll == -1:
            if repeating:
				#APPEND_NEXT_MESSAGE_NO_SCROLL
                script = 'appendNextMessageNoScroll("%@");'
            else:
				#APPEND_MESSAGE_NO_SCROLL
                script = 'appendMessageNoScroll("%@");'
        else:
            if repeating:
				#APPEND_NEXT_MESSAGE
                script = 'appendNextMessage("%@");'
            else:
				#APPEND_MESSAGE
                script = 'appendMessage("%@");'
    
    elif template['style_version'] >= 1:
        
        if repeating:
			#APPEND_NEXT_MESSAGE
            script = 'appendMessage("%@");'
        else:
			#APPEND_MESSAGE
            script = 'appendMessage("%@");'
        
    else:
        
        if repeating:
			#APPEND_NEXT_MESSAGE_WITH_SCROLL
            script = 'checkIfScrollToBottomIsNeeded(); appendNextMessage("%@"); \
               scrollToBottomIfNeeded();'
        else:
			#APPEND_MESSAGE_WITH_SCROLL
            script = 'checkIfScrollToBottomIsNeeded(); appendMessage("%@"); \
               scrollToBottomIfNeeded();'

    return script  



def available_variants(style_path):
    """return an array containing all availables variants"""
    return path_for_resources_of_type_in_directory\
    ("css", style_path + "Variants")


def path_for_variant(variant = None):
	"""return the variant path"""
	if template['style_version'] < 3 and not variant == None
		# styles before v3 stored the default variant in main.css
		return "main.css"
	else
		return "Variants/" + variant + ".css"
